import React, { useEffect } from 'react';
import { connect } from 'react-redux';
import * as actionTypes from './store/actionCreators';
import Slider from '../../components/slider';
import RecommendList from '../../components/list';
import Scroll from '../../baseUI/scroll/index';
import Loading from '../../baseUI/loading/index';
import { Content } from './style';
import { forceCheck } from 'react-lazyload';
import { renderRoutes } from 'react-router-config';

// 映射Redux全局的state到组件的props上
const mapStateToProps = (state) => {
  return {
  // 不要在这里将数据toJS
  // 不然每次diff对比props的时候都是不一样的引用 还是导致不必要的重渲染 属于滥用 immutable
    bannerList: state.getIn(['recommend', 'bannerList']),
    recommendList: state.getIn(['recommend', 'recommendList']),
    enterLoading: state.getIn(['recommend', 'enterLoading']),
}};

// 映射dispatch 到 props上
const mapDispatchToProps = (dispatch) => {
  return {
    getBannerDataDispatch() {
      dispatch(actionTypes.getBannerList());
    },
    getRecommendListDataDispatch() {
      dispatch(actionTypes.getRecommendList());
    },
  }
};

function Recommend(props) {
  const { bannerList, recommendList, enterLoading } = props;
  const { getBannerDataDispatch, getRecommendListDataDispatch } = props;

  useEffect(() => {
    if (!bannerList['size']) {
      getBannerDataDispatch();
    };

    if (!bannerList['size']) {
      getRecommendListDataDispatch();
    };

    // eslint-disable-next-line
  }, []);

  const bannerListJS = bannerList ? bannerList.toJS() : [];
  const recommendListJS = recommendList ? recommendList.toJS() : [];
  
  return (
    <div>
      <Content>
        { renderRoutes (props.route.routes) }
        {/*  @ts-ignore */}
        <Scroll className="list" onScroll={forceCheck}>
          <div>
            <Slider bannerList={bannerListJS}></Slider>
            <RecommendList recommendList={recommendListJS}></RecommendList>
          </div>
        </Scroll>
        { enterLoading ? <Loading></Loading> : null};
      </Content>
    </div>
  )
};

// 将UI组件包装成容器组件
export default connect(mapStateToProps, mapDispatchToProps)(React.memo(Recommend));